<template>
     <div class="dashboard-container">
        <!-- 筛选查询 -->
        <el-form :inline="true">
            <el-form-item label="客户名称">
                <el-input placeholder="请输入客户名" v-model="params.realName" clearable></el-input>
            </el-form-item>
            <el-form-item label="号码">
                <el-input placeholder="请输入号码" v-model="params.phone" clearable></el-input>
            </el-form-item>
            <el-button type="primary" @click="getList">查询</el-button>
        </el-form>

        <!-- 数据 -->
        <el-table :data="list" v-loading="loading">
            <el-table-column type="index" label="序号"></el-table-column>
            <el-table-column prop="person.realName" label="客户名称"></el-table-column>
            <el-table-column prop="person.levelName" label="客户级别"></el-table-column>
            <el-table-column prop="person.phone" label="号码"></el-table-column>
            <el-table-column prop="person.user.nickName" label="归属用户"></el-table-column>
            <el-table-column prop="createTime" label="添加时间"></el-table-column>
            <el-table-column  label="操作" width="200px">
            <template slot-scope="{row}">
                <el-button type="text" @click="handleCall(row)">小号拨打</el-button>
                <el-button type="text" @click="handleUpdate(row)">编辑</el-button>
                <el-button type="text" @click="handleDetail(row)">客户详情</el-button>
                <el-button type="text" @click="handleRelase(row)">放回公海</el-button>
            </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div style="padding-top:30px; text-align: right;">
            <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="params.pageIndex+1"
            background
            :page-sizes="[10, 20, 30, 40]"
            :page-size="params.pageCount"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
            </el-pagination>
        </div>

        <el-dialog :visible.sync="dialogVisible" title="编辑客户信息">
            <el-form label-width="100px" :model="temp" ref="ruleForm">
                <el-form-item label="客户姓名" prop="realName">
                    <el-input v-model="temp.realName" placeholder="请输入客户姓名"></el-input>
                </el-form-item>
            </el-form>
            <div style="text-align: right;">
                <el-button @click="dialogVisible=false">取消</el-button>
                <el-button type="primary" @click="submitForm('ruleForm')">确认</el-button>
            </div>
        </el-dialog>

     </div>
</template>
<script>
import { personGetlist, personRelease, personUpdate } from '@/api/person'
import { callCreate2 } from '@/api/call'
import { collectionGetPersonList } from '@/api/collection'
import moment from 'moment';
import SIP from 'jssip';
import { Session } from 'sip.js';

export default {
    data(){
        return {
            params: {
                pageCount: 10,
                pageIndex: 0,
                dataId: 0,
                phone: '',
                realName: ''
            },
            list: [],
            total: 0,
            loading: false,
            dialogVisible: false,
            temp: {
                dataId: '',
                realName: ''
            },
            ua: null, //sip电话对象
        }
    },
    mounted(){
        this.getList();
    },
    methods: {
        // async handleCall(){
        //     try{
        //         const session = new Session({
        //             uri: 'sip:17314464158@101.132.167.145:12160',
        //             ws_server: 'wss://robot.yuliu8.com:7443',
        //             events_listener: {
        //                 onAccepted: (response) => {
        //                     console.log('Call answered');
        //                 },
        //                 onFailed: (response, cause) => {
        //                     console.log(response, cause,'Call failed');
        //                 },
        //                 onTerminated: (message, cause) => {
        //                     console.log('Call terminated');
        //                 }
        //             }
        //         })
        //         // 发起呼叫
        //         await session.start({
        //             // 本地媒体流
        //             mediaStream: await navigator.mediaDevices.getUserMedia({ audio: true, video: false }),
        //             // 支持的媒体格式
        //             options: {
        //                 mediaConstraints: { audio: true, video: false }
        //             }
        //         });
        //     }catch(error){
        //         console.log(error)
        //     }
        // },
        // 点击sip拨号
        async handleCall(row){
            let callData = await callCreate2({ 
                collectionId: row.collectionId,
                remoteNum: row.person.phone, 
                type: 2,
                personId: row.personId,
                dialogFlag: 0,
                prologueFlag: 0,
                cardNum: '',
                localNum: ''
            })
            SIP.C.SESSION_EXPIRES = 120;
            SIP.C.MIN_SESSION_EXPIRES = 120;
            var socket = new SIP.WebSocketInterface('wss://robot.yuliu8.com:7443');
            console.log('sip:17314464158@101.132.167.145:12160')
            console.log('1724231669957')
            this.ua = new SIP.UA({
                uri: `sip:17314464158@101.132.167.145:12160`, //sip地址
                password: '1724231669957', //你的sip密码
                sockets: [socket],
                register: true,
                connection_recovery_max_interval: 60, // 链接恢复的最大间隔
                connection_recovery_min_interval: 5, // 链接恢复的最小间隔
                iceServers: [{
                    "url": "stun:stun.l.google.com:19302"
                }]
            })
            this.ua.start();
            this.ua.on('registered', async (data) => {
                console.log('注册成功', data)
                const target = 'sip:app_18368041445_' + callData.data.callId+'@101.132.167.145:12160';
                console.log(target)
                var eventHandlers = {
                    'progress': function(err){console.log(err, "呼叫中")},
                    'failed': function(err){console.log(err, "失败")},
                    'confirmed': function(err){console.log(err, "接受电话")},
                    'ended': function(err){console.log(err, "结束")},
                }
                var options = {
                    'eventHandlers': eventHandlers,
                    // 'extraHeaders': [ 'X-Foo: foo', 'X-Bar: bar' ],
                    'mediaConstraints': {'audio': true, 'video': false},
                    // 'sessionTimersExpires': 500
                }
                const call = this.ua.call(target, options);
            });
        },
        submitForm(formName){
            this.$refs[formName].validate(async (valid) => {
                if (valid) {
                    let temp;
                    temp = Object.assign({}, this.temp)
                    await personUpdate(temp)
                    this.dialogVisible = false;
                    this.getList();
                } else {
                    console.log('error submit!!');
                    return false;
                }
          });
        },
        //点击编辑
        handleUpdate(row){
            this.temp = {
                dataId: row.person.id,
                realName: row.person.realName
            }
            this.dialogVisible = true
        },
        handleDetail(row){
            this.$router.history.push({ path: '/crm/detail?id='+row.person.id })
        },
        // 放回公海 - 单个
        async handleRelase(row){
            await personRelease({ dataIds: [row.person.id] })
            this.$message.success({ message: '操作成功' })
            this.getList();
        },

        async getList(){
            this.loading = true;
            let data = await collectionGetPersonList(this.params)
            this.loading = false;
            this.list = data.data.list.map(item=>{
                item.createTime = moment(item.createTime).format('YYYY-MM-DD HH:mm:ss')
                item.person.levelName = item.person.levelStyles.map(item=>item.name).join(',')
                return item;
            })
            this.total = data.data.totalCount
        },

        //切换数量
        handleSizeChange(val){
            this.params.pageIndex = 0;
            this.params.pageCount = val;
            this.getList();
        },

        //切换页码
        handleCurrentChange(val){
            this.params.pageIndex = val-1;
            this.getList();
        }
    }
}
</script>

<style lang="scss" scoped>
.dashboard {
  &-container {
    margin: 30px;
    
  }
}
</style>